<template>
  <div
    class="container"
  >
    <div class="columns" style="width: 100%">
      <div class="column">
        <div class="field">
          <div class="label">博客标题</div>
          <div class="control">
            <input
              type="text"
              class="input"
              data-test="post-title"
              v-model="title"
            />
          </div>
        </div>
      </div>
    </div>
    <div
      class="columns"
      style="display: flex; flex-direction: row; width: 100%"
    >
      <div class="column" style="width: 50%">
        写的内容
        <div
          style="text-align: left"
          contenteditable
          id="markdown"
          @input="handleEdit"
          ref="contentEditable"
          data-test="markdown"
        />
      </div>
      <div class="column" style="width: 50%">
        <div v-html="html"></div>
      </div>
    </div>
    <!-- 保存 -->
    <div class="columns">
      <div class="column" style="display:flex;justify-content:space-between;">
        
        <button
        @click="$router.go(-1)"
          data-test="submit-post"
          class="button is-danger "
        >
          取消
        </button>
        <button
          data-test="submit-post"
          class="button is-primary"
          @click="handleSubmit"
        >
          保存
        </button>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Post } from "@/types";
import { defineComponent, onMounted, ref, watch } from "vue";
// @ts-ignore
import { parse, MarkedOptions } from "marked";
import { highlightAuto } from "highlight.js";
import debounce from "lodash/debounce";
export default defineComponent({
  name: "PostWriter",
  emits: ["save"],
  props: {
    post: {
      type: Object as () => Post,
      required: true,
    },
  },
  components: {},
  setup(props, ctx) {
    const title = ref(props.post.title);
    const contentEditable = ref<null | HTMLDivElement>(null);
    const markdown = ref(props.post.markdown);
    const html = ref("");

    const options: MarkedOptions = {
      highlight: (code: string) => highlightAuto(code).value,
    };
    const update = (value: string) => {
      console.log(value);
      html.value = parse(value, options);
    };

    const handleSubmit = () => {
      const post: Post = {
        ...props.post,
        title: title.value,
        markdown: markdown.value,
        html: html.value,
      };
      ctx.emit("save", post);
    };
    watch(() => markdown.value, debounce(update, 500), { immediate: true });
    onMounted(() => {
      // @ts-ignore
      contentEditable.value.innerText = markdown.value;
    });

    console.log(parse(markdown.value));
    const handleEdit = () => {
      // @ts-ignore
      markdown.value = contentEditable.value.innerText;
    };
    return { title, contentEditable, handleEdit, markdown, html, handleSubmit };
  },
});
</script>